var domain;
var tabn;
var w;
var t;
var code;

function getDomain(url){
     var host = "null";
     if(typeof url == "undefined" || null == url)
          url = window.location.href;
     var regex = /.*\:\/\/([^\/]*).*/;
     var match = url.match(regex);
     if(typeof match != "undefined" && null != match)
          host = match[1];
     return host;
}

function checkUrl(tabId, changeInfo, tab) {	
	chrome.pageAction.show(tabId);
	tabn = tabId;
	domain = getDomain(tab.url);
	if (domain == 'newtab' || domain == 'extensions' || domain == 'chrome') {
		w='<img src=icon.png><br>作者：海天鹰<br>QQ：84429027';
	} else {
		xmlhttprequest('http://ip-api.com/json/' + domain);
	}
};

function xmlhttprequest(url) {	
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
				if (typeof(JSON) == 'undefined'){
					data = eval("(" + xhr.responseText + ")");
				}else{
					data = JSON.parse(xhr.responseText);
				}			
				code = data.countryCode+'';
				d = new Date();
				time = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
				w = '<button id=refresh><img src=refresh.svg></button><br>域名：' + domain + '<br>AS：' + data.as + '<br>城市：' + data.city + '，' + data.regionName + '，' + data.country + '<br>ISP：' + data.isp + '<br>纬经度：<a href=https://maps.google.com/maps?t=m&q=' + data.lat + ',' + data.lon + ' target=_blank>' + data.lat + '，' + data.lon + '</a><br>组织：' + data.org + '<br>IP：<a href=http://' + data.query + ' target=_blank>' + data.query + '</a><br>刷新时间：' + time;
				t = '域名：' + domain + '\n城市：' + data.city + '，' + data.regionName + '，' + data.country + '\nISP：' + data.isp + '\n纬经度：' + data.lat + '，' + data.lon + '\nIP：' + data.query + '\n刷新时间：' + time;
				chrome.pageAction.setTitle({ tabId: tabn, title: t });
				chrome.pageAction.setIcon({ tabId: tabn, path: 'flags/' + code + '.png' });
			} else {
				console.log(url + ' 错误');
			}
        }
      }
      xhr.open('GET', url, false);
      xhr.send();
};

chrome.tabs.onUpdated.addListener(checkUrl);

chrome.tabs.onActivated.addListener(function (activeInfo) {
    chrome.tabs.get(activeInfo.tabId, function (tab) {        
		chrome.pageAction.show(activeInfo.tabId);
		domain = getDomain(tab.url);
		tabn = activeInfo.tabId;
		if(domain == 'newtab' || domain == 'extensions' || domain == 'chrome'){
			w = '<img src=icon.png><br>作者：海天鹰<br>QQ：84429027';
		} else {
			if (domain != 'devtools') {
				xmlhttprequest('http://ip-api.com/json/' + domain);
			}
		}
    });
});